﻿#ifndef __SS_SNOWFLAKE_H__
#define __SS_SNOWFLAKE_H__
#include <time.h>
#include "../thread/threadLock/ssAtomicLock.h"
#include <string>

#define SS_SNOW_BEGIN_TIMESTAMP 1669824000 //2022-12-01零点时间戳
#define SS_SNOW_MAX 262143 //自增最大值
#define SS_SNOWWT_MAX 1125899906842624ll

namespace StarSeeker
{

//32位时间戳+14位serverID+18位自增值
class ssSnowflake
{
public:
	ssSnowflake();
	ssSnowflake(unsigned short serverID, int timeStampBegin=SS_SNOW_BEGIN_TIMESTAMP);
	~ssSnowflake();

	//初始化
	void Init(unsigned short serverID, int timeStampBegin=SS_SNOW_BEGIN_TIMESTAMP);
	//获取ID
	long long GetID();
	//解析ID
	static unsigned int ParseTimeStamp(long long id);
	static unsigned short ParseServerId(long long id);
	static unsigned int ParseServerInc(long long id);
	//10进制转36进制
	static std::string Adecimal10ToAdecimal36(long long num);
	static long long Adecimal36ToAdecimal10(std::string& strNo);
private:
	time_t			m_timeStamp;
	unsigned int	m_inc;
	unsigned short	m_serverID;
	time_t			m_timeStampBegin;
};

class ssSafeSnowflake : public ssSnowflake
{
public:
	long long GetSafeID();

private:
	ssAtomicLock	m_lock;
};

//14位serverID+50位自增值
class ssSnowflakeWT
{
public:
	ssSnowflakeWT();
	ssSnowflakeWT(unsigned short serverID);
	~ssSnowflakeWT();

	//初始化
	void Init(unsigned short serverID);
	//获取ID
	long long GetID();
	//解析ID
	static unsigned short ParseServerId(long long id);
	static long long ParseServerInc(long long id);
private:
	long long				m_inc;
	long long				m_serverID;
};

class ssSafeSnowflakeWT : public ssSnowflakeWT
{
public:
	long long GetSafeID();

private:
	ssAtomicLock	m_lock;
};

}
#endif
